package com.zlx.exchange.admin.controller;

import cn.hutool.jwt.JWT;
import com.alibaba.nacos.common.utils.StringUtils;

import com.zlx.exchange.admin.service.AdminService;
import com.zlx.exchange.domain.entity.Admin;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * (Admin)表控制层
 *
 * @author makejava
 * @since 2023-09-08 10:17:07
 */
@RestController
@RequestMapping("api/admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Resource
    private AdminService adminService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 登录，并创建jwt
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("loginByUserName")
    public ResponseEntity<?> loginByUserName(String username, String password) {
        Admin admin= adminService.queryByUsername(username, password);
        if (Objects.isNull(admin)) {
            return ResponseEntity.status(1).body("账号或密码错误");
        }
        String jwt = JWT.create().setKey(admin.getKey().getBytes())
                .setPayload("username", admin.getUsername())
                .setPayload("role", admin.getRoleId())
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 30))
                .sign();
        redisTemplate.opsForValue().set("user" + admin.getId(), jwt, 30, TimeUnit.MINUTES);
        return ResponseEntity.ok().body(jwt);
    }

    @PostMapping("register")
    public ResponseEntity<?> register(String username, String password) {
        if (StringUtils.isAnyBlank(username, password)) {
            return ResponseEntity.status(2).body("不可为空");
        }
        if (adminService.register(username, password)) {
            return ResponseEntity.ok("注册成功");
        }
        else return ResponseEntity.status(3).body("注册失败");
    }

}

